import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:yysk_app/enum/app_enum.dart';
import 'package:yysk_app/main.dart';
import 'package:yysk_app/model/collection_model/home_first_list_model.dart';
import 'package:yysk_app/model/common_model/banner_list_model.dart';
import 'package:yysk_app/model/common_model/notice_list_model.dart';
import 'package:yysk_app/net/api/api_url.dart';
import 'package:yysk_app/net/api/common_api.dart';
import 'package:yysk_app/net/api/product_api.dart';
import 'package:yysk_app/net/http.dart';
import 'package:yysk_app/pages/login/login_page.dart';
import 'package:yysk_app/routes/global_controller.dart';
import 'package:yysk_app/utils/check_for_updates.dart';
import 'package:yysk_app/utils/js_tool.dart';
import 'package:yysk_app/utils/switch_mode_pop.dart';

class MainController extends GetxController {
  late MainController controller;
  late PageController pageController;
  //邀请码输入框控制器invited
  final TextEditingController invitedController = TextEditingController();
  final invitedCode = ''.obs;
  //判断是否聚焦
  final FocusNode focusNode = FocusNode();
  final isFocused = false.obs;
  //banner
  final bannerList = RxList<BannerListItem>();
  //公告
  final noticeList = RxList<NoticeListItem>();
  //首发数据
  final homeList = RxList<HomeFirstListItem>();
  final selectType = 'PLATFORM'.obs;
  int fristPage = 1;
  //切换导航
  final modeType = AppModel.nft.obs;
  late final BuildContext? mainContext =
      navigatorKey.currentState?.overlay?.context;

  final currentIndex = 0.obs;
  final loading = false.obs;
  //实名，钱包开通
  final hasAuth = false.obs;
  final hasWallet = false.obs;

  var tabIndex = '';
 // 创建一个 GlobalKey 来控制 Scaffold
  final GlobalKey<ScaffoldState> mainScaffoldKey = GlobalKey<ScaffoldState>();

  int boutiqueGiftPage = 1;
  int selectedIndex = 0;
  void changeIndex({required int index, String type = '0'}) {
    if (index == currentIndex.value) {
      return;
    }
    if (index == 2 && modeType.value == AppModel.nft) {
      //我的页面
      GlobalController globalController = Get.find();
      globalController.getUserInfo();
      // return;
    }

    pageController.jumpToPage(index);
    currentIndex.value = index;
  }

  // 获取验证实名，钱包开户信息
  void getStatus() {
    http.netFetch<dynamic>(
      '',
      success: (result) {
        // hasAuth.value = result.data?.isSm ?? false;
        // hasWallet.value = result.data?.isOpenWallet ?? false;
        // saveToLocalStorage(
        // 'hasWallet', '${result.data?.isOpenWallet ?? false}');
      },
    );
  }

  //获取 banner数据
  void getBarnnerList() {
    http.netFetch<BannerListModel>(
      CommonApi.bannerList,
      params: {'pageSize': 20, 'pageNum': 1},
      method: Method.post,
      success: (result) {
        bannerList.value = result.data!.list!;
      },
    );
  }

  //获取 notice公告数据
  void getNoticeList() {
    http.netFetch<NoticeListModel>(
      CommonApi.noticeList,
      params: {'pageSize': 6, 'pageNum': 1},
      method: Method.post,
      success: (result) {
        noticeList.value = result.data!.list ?? [];
      },
    );
  }

  //获取首发列表，品牌首发列表，盲盒列表
  //获取首发列表，品牌首发列表，心愿盒列表
  Future<void> getProductList({loadMore = false}) {
    if (loadMore) {
      fristPage++;
    } else {
      fristPage = 1;
    }
    try {
      return http.netFetch<HomeFirstListModel>(
        ProductApi.firstPublish,
        method: Method.post,
        params: {
          'pageSize': 10,
          'pageNum': fristPage,
          'productLocation': selectType.value,
        },
        success: (result) {
          List<HomeFirstListItem> items = result.data?.list ?? [];

          if (loadMore && items.isEmpty) {
            fristPage--;
          }
          if (!loadMore) {
            homeList.clear();
          }
          homeList.addAll(items);
        },
      );
    } catch (e) {
      debugPrint(e.toString());

      if (loadMore) {
        fristPage--;
      }
      return Future.error(e);
    }
  }

  @override
  void onInit() {
    super.onInit();
    //检查版本更新
    fetchVersionInfo().then((res) {
      chech_updata(res: res, context: Get.context!);
    });
    pageController = PageController();
    //监听
    modeType.listen((value) {
      switchModePop(context: mainContext!, type: value);
      Future.delayed(Duration(milliseconds: 1500), () {
        consoleLog('${Get.context}');
        final currentRoute = Get.currentRoute ?? '/unknown';
        if (currentRoute != LoginPage.path) {
          Navigator.pop(mainContext!); //
        }
      });
    });
    //监听聚焦
    focusNode.addListener(() {
      isFocused.value = focusNode.hasFocus;
    });
    //初始化
    getBarnnerList();
    getNoticeList();
    getProductList();
  }

  @override
  void onClose() {
    super.onClose();
    pageController.dispose();
    focusNode.dispose();
  }
}
